﻿using Microsoft.Extensions.DependencyInjection;
using System;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace DbContextString
{
    class Program
    {
        static async Task Main()
        {
            var p = new Program();
            //初始化EF服务容器
            p.InitializeServices();
            //添加日志到控制台
            p.ConfigureLogging();
            //通过依赖注入容器获得BooksService实例
            var service = p.Container.GetService<CollectService>();

            await service.CreateDatabaseAsync();
            //添加书本到数据库
            await service.AddCollectAsync();
            //读取数据库中的数据
            await service.ReadCollectAsync();
            //释放容器资源
            p.Container.Dispose();
        }

        private void InitializeServices()//连接
        {
            const string ConnectionString =
              @"server=(localdb)\MSSQLLocalDb;database=Collect;trusted_connection=true";
            //创建ServiceCollection实例
            var services = new ServiceCollection();
            //注册瞬时实例BooksService
            services.AddTransient<CollectService>()
              .AddEntityFrameworkSqlServer()//注册EF和SQLSERVER
                                            //将上下文添加到服务容器忠
              .AddDbContext<CollectContext>(options =>
                options.UseSqlServer(ConnectionString));//设置上下文选项为使用SQL服务器并设置连接字符串
            services.AddLogging();//添加日志
            //创建服务容器
            Container = services.BuildServiceProvider();
        }
        public ServiceProvider Container { get; private set; }

        private void ConfigureLogging()
        {
            //从服务容器中获取日志工厂
            ILoggerFactory loggerFactory = Container.GetService<ILoggerFactory>();
            //日志消息送入控制台
            loggerFactory.AddConsole(LogLevel.Information);
        }
    }

}
